//
//  GGBLEViewController.m
//  03-CL-Lock
//
//  Created by 陈志勇 on 16/9/23.
//  Copyright © 2016年 陈志勇. All rights reserved.
//

#import "GGBLEViewController.h"
#import "BLECentralManager.h"
#import <MJRefresh/MJRefresh.h>
#import "GGDownLoadViewController.h"
#import "GGDFUProtocol.h"
#import "GGMD5.h"
#import "GGBaseInfoData.h"

#import "GGBLEManager.h"

@interface GGBLEViewController ()<UITableViewDelegate,UITableViewDataSource>

//@property(strong,nonatomic) BLECentralManager *manager;
@property(strong,nonatomic) NSArray *peripheralList;

@property(strong,nonatomic) GGBLEManager *manager;

@end




@implementation GGBLEViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //初始化
//    _manager = [BLECentralManager shareInstance];
//    
//    [_manager cancelAllConnect];
//    
//    //开始扫描
//    [_manager startScan];
//  
//    // 下拉刷新
//    self.tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        //开始扫描
//        [_manager startScan];
//        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            // 结束刷新
//            [self.tableView.mj_header endRefreshing];
//            [self.tableView reloadData];
//        });
//    }];
    
    
    _manager = [GGBLEManager getInstance];
    
    [_manager cancelPeripheralWith:nil];
    
    //开始扫描
    [_manager startScan];
    
    [_manager getBlueListArray:^(NSMutableArray *blueToothArray) {
        _peripheralList = [_manager getNameList];
        [self.tableView reloadData];
    }];
    
    // 下拉刷新
    self.tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //开始扫描
        [_manager startScan];
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 结束刷新
            [self.tableView.mj_header endRefreshing];
            _peripheralList = [_manager getNameList];
            [self.tableView reloadData];
        });
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"蓝牙列表";
//
//    //只有数据的才显示分割线，同时不能设置separatorStyle
//    self.tableView.tableFooterView = [[UIView alloc] init];
//    
//    //初始化
//    _manager = [BLECentralManager shareInstance];
//    
//    //开始扫描
//    [_manager startScan];
//    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upDateBLEListInfo:) name:kBLEScanCompletedNotification object:nil];
    
    
    //只有数据的才显示分割线，同时不能设置separatorStyle
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    //定时获取蓝牙列表数据
    [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(getNameListInfo) userInfo:nil repeats:NO];
}

//获取蓝牙列表数据
- (void)getNameListInfo{
    
    _peripheralList = [_manager getNameList];
    [self.tableView reloadData];
    
}

//刷新蓝牙列表
- (void)upDateBLEListInfo:(NSNotification *)notify{
    
    _peripheralList = notify.object;
    [self.tableView reloadData];
}

- (void)dealloc{
    // 移除观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kBLEScanCompletedNotification object:nil];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _peripheralList.count;
}


//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    // 0.重用标识
//    static NSString *ID = @"cell";
//    
//    // 1.先根据cell的标识去缓存池中查找可循环利用的cell
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//    
//    // 2.如果cell为nil（缓存池找不到对应的cell）
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
//    }
//    
//    BLEDeviceInfo *device = _peripheralList[indexPath.row];
//    cell.textLabel.text = device.peripheral.name;
//    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@,%@",device.rssi,[device.peripheral.identifier UUIDString]];
//    
//    return cell;
//}
//
//
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    
//    BLEDeviceInfo *device = _peripheralList[indexPath.row];
//    [_manager beginConnectWithPeripheral:device.peripheral];
//    
//    
//    [[BLECentralManager shareInstance] setConnectedCompletionBlock:^(CBPeripheral *peripheral) {
//        
//        NSLog(@"蓝牙连接成功：BLOCK回调");
//        // 停止扫描
//        [[BLECentralManager shareInstance] stopScan];
//        
//        // 跳转
//        GGDownLoadViewController *downloadVC = [[GGDownLoadViewController alloc] init];
//        [self.navigationController pushViewController:downloadVC animated:YES];
//    }];
//}
//#pragma mark - 测试用代码，可删除
//- (void)testCode{
//    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"ChaXinSuoJHB_LanYa_GSJMXYV2_10" ofType:@"bin"];
//    // 计算读取的文件MD5
//    NSString *md5 = [GGMD5 getFileMD5WithPath:filePath];
//    //MD5共有16个字节，根据协议需要截取MD5的前8个字节当做MD5的校验结果
//    md5 = [md5 substringToIndex:16];
//    md5 = [NSString stringWithFormat:@"%@0800",md5];
//    // 引导握手
//    GGBaseInfoData *infoData = [[GGBaseInfoData alloc] init];
//    infoData.packetIndex = 0;
//    infoData.commandType = GGBaseInfoDataCommandHandShake;
//    infoData.infoLength = 10;
//    infoData.infoData = [GGDFUProtocol hexStringToData:md5];
//    NSData *tempData = [infoData encodeInfoData];
//    tempData = [GGDFUProtocol encodeDataWithInfoData:tempData commandType:GGDFUCommandTypeDownload];
//    NSLog(@"引导握手命令:%@",tempData);
//    [[BLECentralManager shareInstance].getFirstConnector sendData:tempData];
//
//    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
//    
//    NSInteger count = [fileData length] / 1024 + 1;
//    
//    for (int i = 0; i < count; i++) {
//        
//        NSData *data = [[NSData alloc] init];
//        
//        if (i == count - 1) {
//            data = [fileData subdataWithRange:NSMakeRange(1024 * i, [fileData length] - 1024 * i)];
//        }else{
//            data = [fileData subdataWithRange:NSMakeRange(1024 * i, 1024)]; //截取数据
//        }
//        GGBaseInfoData *infoData = [[GGBaseInfoData alloc] init];
//        infoData.packetIndex = i + 1;
//        infoData.commandType = GGBaseInfoDataCommandTpyeDownload;
//        infoData.infoLength = [data length];
//        infoData.infoData = data;
//        data = [infoData encodeInfoData];
//        //        [GGDFUProtocol msrKeyWithCommandType:GGDFUCommandTypeDownload contentInfo:data];
//        data = [GGDFUProtocol encodeDataWithInfoData:data commandType:GGDFUCommandTypeDownload];
//        
//        NSLog(@"组包好的数据：%@",data);
//    }
//}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 0.重用标识
    // 被static修饰的局部变量：只会初始化一次，在整个程序运行过程中，只有一份内存
    static NSString *ID = @"cell";
    
    // 1.先根据cell的标识去缓存池中查找可循环利用的cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    // 2.如果cell为nil（缓存池找不到对应的cell）
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
    }
    
    NSDictionary *dic = _peripheralList[indexPath.row];
    CBPeripheral *per = [dic objectForKey:@"peripheral"];
    NSNumber *RSSI = [dic objectForKey:@"RSSI"];
    //    CBPeripheral *per = _peripheralList[indexPath.row];
    cell.textLabel.text = per.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@,%@",RSSI,[per.identifier UUIDString]];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dic = _peripheralList[indexPath.row];
    CBPeripheral *per = [dic objectForKey:@"peripheral"];
    
    // 连接蓝牙
    [_manager connectPeripheralWith:per];
    
    //如果成功连接外设后，回调该函数
    [_manager connectInfoReturn:^(CBCentralManager *central, CBPeripheral *peripheral, NSString *stateStr) {
        
        if ([stateStr isEqualToString:@"SUCCESS"]) {
            
            NSLog(@"蓝牙连接成功");
            
            // 连接成功后，转到下个界面
            // 加载storyboard
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            
            // 根据蓝牙名称不同，创建响应的调试控制器
            if ([_manager.thePeripheral.name isEqualToString:IKeyName] || [_manager.thePeripheral.name isEqualToString:IKeyName2] || [_manager.thePeripheral.name isEqualToString:IKeyName3] ) {
//                GGDebugViewController *DebugVC = [storyboard instantiateViewControllerWithIdentifier:@"debug"];
//                DebugVC.manager = _manager;
//                [self.navigationController pushViewController:DebugVC animated:YES];
            }
            if ([_manager.thePeripheral.name isEqualToString:ILockName]) {
//                GGBluetoothLockDebugVC *bluetoothLockDebugVC = [storyboard instantiateViewControllerWithIdentifier:@"Bluetoothlockdebug"];
//                
//                bluetoothLockDebugVC.manager = _manager;
//                [self.navigationController pushViewController:bluetoothLockDebugVC animated:YES];
            }
            if ([_manager.thePeripheral.name hasPrefix:@"SCTT"] ||[_manager.thePeripheral.name hasPrefix:@"SDTT"] ||[_manager.thePeripheral.name hasPrefix:@"elock key"]) {
//                SDTTSJVC *testSJVC = [storyboard instantiateViewControllerWithIdentifier:@"testSJVC"];
//                testSJVC.manager = _manager;
//                [self.navigationController pushViewController:testSJVC animated:YES];
            }
            if ([_manager.thePeripheral.name hasPrefix:@"FJTT"]) {
                GGDownLoadViewController *downLoadVc = [[GGDownLoadViewController alloc] init];
                [self.navigationController pushViewController:downLoadVc animated:YES];
            }
            
            [_manager stopScan];
            //            GGDebugViewController *DebugVC = [storyboard instantiateViewControllerWithIdentifier:@"debug"];
            //            DebugVC.manager = _manager;
            //            [self.navigationController pushViewController:DebugVC animated:YES];
        }
    }];
    
}
@end
